const k8s = require('@kubernetes/client-node');

// 创建Kubernetes配置
const kc = new k8s.KubeConfig();

// 根据环境加载配置
if (process.env.KNATIVE_MODE === 'local' || !process.env.KNATIVE_MODE) {
  // 本地开发环境使用默认配置
  kc.loadFromDefault();
} else {
  // 生产环境可以从环境变量或指定路径加载配置
  kc.loadFromCluster();
}

// 创建自定义对象API客户端
const k8sApi = kc.makeApiClient(k8s.CustomObjectsApi);

// Knative Serving API组和版本
const GROUP = 'serving.knative.dev';
const VERSION = 'v1';
const PLURAL = 'services';

/**
 * 部署函数到Knative
 * @param {Object} func - 函数对象
 * @returns {Promise<Object>} 部署结果
 */
async function deployFunction(func) {
  try {
    const namespace = process.env.KNATIVE_NAMESPACE || 'default';
    
    // 构建Knative Service对象
    const knService = {
      apiVersion: `${GROUP}/${VERSION}`,
      kind: 'Service',
      metadata: {
        name: func.name,
        labels: {
          'function-manager': 'true',
          'function-id': func.id
        }
      },
      spec: {
        template: {
          metadata: {
            labels: {
              'function-id': func.id
            }
          },
          spec: {
            containers: [
              {
                image: func.image,
                env: buildEnvVariables(func.env),
                ports: [
                  {
                    containerPort: 8080
                  }
                ],
                resources: {
                  requests: func.requests || {},
                  limits: func.limits || {}
                }
              }
            ]
          }
        }
      }
    };

    // 尝试创建或更新服务
    try {
      const response = await k8sApi.createNamespacedCustomObject(
        GROUP,
        VERSION,
        namespace,
        PLURAL,
        knService
      );
      
      return {
        success: true,
        message: '函数部署成功',
        service: response.body
      };
    } catch (createError) {
      // 如果服务已存在，尝试更新
      if (createError.statusCode === 409) {
        const response = await k8sApi.patchNamespacedCustomObject(
          GROUP,
          VERSION,
          namespace,
          PLURAL,
          func.name,
          knService,
          undefined,
          undefined,
          undefined,
          {
            headers: {
              'Content-Type': 'application/merge-patch+json'
            }
          }
        );
        
        return {
          success: true,
          message: '函数更新成功',
          service: response.body
        };
      }
      
      throw createError;
    }
  } catch (error) {
    console.error('部署到Knative失败:', error);
    return {
      success: false,
      message: '函数部署失败',
      error: error.message
    };
  }
}

/**
 * 构建环境变量数组
 * @param {Object} envObj - 环境变量对象
 * @returns {Array} 环境变量数组
 */
function buildEnvVariables(envObj) {
  if (!envObj) return [];
  
  return Object.entries(envObj).map(([name, value]) => ({
    name,
    value: String(value)
  }));
}

/**
 * 获取服务状态
 * @param {string} serviceName - 服务名称
 * @returns {Promise<Object>} 服务状态信息
 */
async function getServiceStatus(serviceName) {
  try {
    const namespace = process.env.KNATIVE_NAMESPACE || 'default';
    
    const response = await k8sApi.getNamespacedCustomObject(
      GROUP,
      VERSION,
      namespace,
      PLURAL,
      serviceName
    );
    
    const service = response.body;
    const status = service.status || {};
    
    return {
      success: true,
      serviceName,
      status: status.conditions ? status.conditions[0].status : 'Unknown',
      url: status.url || null,
      conditions: status.conditions || []
    };
  } catch (error) {
    console.error('获取服务状态失败:', error);
    return {
      success: false,
      serviceName,
      error: error.message
    };
  }
}

/**
 * 获取所有服务状态
 * @returns {Promise<Array>} 服务状态列表
 */
async function getAllServicesStatus() {
  try {
    const namespace = process.env.KNATIVE_NAMESPACE || 'default';
    
    const response = await k8sApi.listNamespacedCustomObject(
      GROUP,
      VERSION,
      namespace,
      PLURAL
    );
    
    const services = response.body.items || [];
    
    // 提取每个服务的状态信息
    const servicesStatus = services.map(service => {
      const status = service.status || {};
      const conditions = status.conditions || [];
      
      // 获取最新的条件状态
      const latestCondition = conditions.length > 0 ? conditions[0] : null;
      
      return {
        name: service.metadata.name,
        status: latestCondition ? latestCondition.status : 'Unknown',
        url: status.url || null,
        conditions: conditions,
        labels: service.metadata.labels || {}
      };
    });
    
    return {
      success: true,
      services: servicesStatus
    };
  } catch (error) {
    console.error('获取所有服务状态失败:', error);
    return {
      success: false,
      error: error.message
    };
  }
}

/**
 * 删除服务
 * @param {string} serviceName - 服务名称
 * @returns {Promise<Object>} 删除结果
 */
async function deleteService(serviceName) {
  try {
    const namespace = process.env.KNATIVE_NAMESPACE || 'default';
    
    const response = await k8sApi.deleteNamespacedCustomObject(
      GROUP,
      VERSION,
      namespace,
      PLURAL,
      serviceName
    );
    
    return {
      success: true,
      message: '服务删除成功',
      response: response.body
    };
  } catch (error) {
    console.error('删除服务失败:', error);
    return {
      success: false,
      message: '服务删除失败',
      error: error.message
    };
  }
}

module.exports = {
  deployFunction,
  getServiceStatus,
  getAllServicesStatus,
  deleteService
};